<?php
/**
 * Hello Model for Hello World Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
 * @license    GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class calendarsModelcalendars extends JModel
{
    var $_data;
	 var $_buildtype;
	 var $db;
	
	 
	 function __construct()
	{
		parent::__construct();
		$this->db = JFactory::getDBO();
		
		$id = JRequest::getVar('cid', 0, '', 'array');
		$this->setId((int)$id[0]);
	}
	 
	 function _setBuild($type = 'Calendar')
    {
		$this->_buildtype = "_build".ucfirst($type);
		//var_dump($this->_buildtype);
		return "_build".ucfirst($type);
	}
	 
    function _buildCalendar()
    {
        //$query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id  ORDER BY a.ordering, a.start_date, a.start_time';
        $query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.state, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id  ORDER BY a.ordering, a.start_date, a.start_time';
        return $query;
    }
	
	function _buildPublished()
    {
        //$query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id  WHERE a.published = 1 ORDER BY a.ordering, a.start_date, a.start_time';
        $query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.state, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id  WHERE a.state = 1 ORDER BY a.ordering, a.start_date, a.start_time';
        return $query;
    }
	
	function _buildDetail()
    {
		$where = (empty($this->_id)) ? '' : 'a.id = '.$this->_id;
        //$query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id WHERE '.$where.' ORDER BY a.ordering, a.start_date, a.start_time' ;
        $query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.state, a.ordering, a.params, c.title as cat_name  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id WHERE '.$where.' ORDER BY a.ordering, a.start_date, a.start_time' ;
        return $query;
		//var_dump($query);
    }

    /**
     * Retrieves the hello data
     * @return array Array of objects containing the data from the database
     */
    function getData()
    {
		//var_dump('get data');
        // Lets load the data if it doesn't already exist
        if (empty( $this->_data ))
        {
			//var_dump("build ".$this->_buildtype . " type1");
			if(empty($this->_buildtype)){
				$type = $this->_setBuild();
			}else{
				$type = $this->_buildtype;
			}
						//var_dump("build ".$this->_buildtype . " type2");
            $calendar = $this->$type();//$this->_buildCalendar();////$this->_build$type();
						//var_dump("calendar ".$calendar);
            switch($type){
			//case '_buildDetail':
					//$this->db->setQuery($calendar);
					//$this->data = $this->db->loadResult($calendar);
					//break;
				default:
					$this->_data = $this->_getList( $calendar );
					 
						
			}//end switch
			
        }
		/*
		 * We need to unify the introtext and fulltext fields and have the
		 * fields separated by the {readmore} tag, so lets do that now.
		 */
        /*
		if (JString::strlen($this->_data->fulldescription) > 1) {
			$this->_data->description = $this->_data->introtext . "<hr id=\"system-readmore\" />" . $this->_data->fulldescription;
		} else {
			$this->_data->description = $this->_data->introdescription;
		}
*/
		//var_dump($this->_data);
		return $this->_data;
		
    }
	
	///////////////////////////////////////////////////
	/**
	* viewCalendar based on viewContent
	* makes display objs for default view
	*/
	function viewCalendar()
	{
		global $mainframe;

		// Initialize variables
		$db			=& JFactory::getDBO();
		$filter		= null;

		// Get some variables from the request
		//$sectionid			= JRequest::getVar( 'sectionid', -1, '', 'int' );
		//$redirect			= $sectionid;
		$option				= JRequest::getVar( 'option' );
		$context			= 'com_calendar.viewccalendar';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order', 'filter_order', '');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir', 'filter_order_Dir', '');
		$filter_state		= $mainframe->getUserStateFromRequest( $context.'filter_state', 'filter_state', '*');
		$catid				= $mainframe->getUserStateFromRequest( $context.'catid', 'catid', 0);
		//$filter_authorid	= $mainframe->getUserStateFromRequest( $context.'filter_authorid', 'filter_authorid', 0);
		//$filter_sectionid	= $mainframe->getUserStateFromRequest( $context.'filter_sectionid', 'filter_sectionid', -1);
		$search				= $mainframe->getUserStateFromRequest( $context.'search', 'search', '');

		//$limit		= (int) $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 0);
		$limit		= (int) $mainframe->getUserStateFromRequest( $context.'limit', 'limit', 20);
		//$limit		=	(int) JRequest::getVar('limit', $mainframe->getCfg('list_limit'));
		$limitstart	= (int) $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0);

		//$where[] = "c.state >= 0";
		//$where[] = 'c.state != -2';

		if (!$filter_order) {
			$filter_order = 'start_date, start_time';
		}
		$order = ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', start_date, start_time, c.title, c.ordering';
		$all = 1;
		
		/*
		if ($filter_sectionid >= 0) {
			$filter = ' WHERE cc.section = '. $filter_sectionid;
		}
		$section->title = 'All Articles';
		$section->id = 0;
		*/
		
		/*
		 * Add the filter specific information to the where clause
		 */
		// Section filter
		//if ($filter_sectionid >= 0) {
			//$where[] = 'c.sectionid = ' . (int) $filter_sectionid;
		//}
		// Category filter
		if ($catid > 0) {
			$where[] = 'a.catid = ' . (int) $catid;
		}
		// Author filter
		if ($filter_authorid > 0) {
			$where[] = 'a.created_by = ' . (int) $filter_authorid;
		}
		// Content state filter
		
		//if ($filter_state) {
			if ($filter_state == 'P') {
				$where[] = 'a.state = 1';
			} else {
				if ($filter_state == 'U') {
					$where[] = 'a.state = 0';
				} else if ($filter_state == 'A') {
					$where[] = 'a.state = -1';
				} else {
					$where[] = 'a.state >= 0';
				}
			}
		//}
		
		// Keyword filter
		if ($search) {
			$where[] = '(LOWER( a.title ) LIKE ' . $db->Quote( "%$search%" ) .
				' OR a.id = ' . (int) $search . ')';
		}

		// Build the where clause of the content record query
		$where = (count($where) ? ' WHERE '.implode(' AND ', $where) : '');

		// Get the total number of records
		$query = 'SELECT COUNT(*)' .
				' FROM #__calendar AS a' .
				' LEFT JOIN #__categories AS c ON c.id = a.catid' .
				$where;
		//var_dump($query);
		$db->setQuery($query);
		//var_dump($query);
		$total = $db->loadResult();


		// Create the pagination object
		jimport('joomla.html.pagination');
		
		$pagination = new JPagination($total, $limitstart, $limit);

		// Get the articles
		//$query = 'SELECT c.*, g.name AS groupname, cc.title AS name, u.name AS editor, f.content_id AS frontpage, s.title AS section_name, v.name AS author' .
		$query = 'SELECT a.id, a.title, a.start_date, a.start_time, a.introdescription, a.fulldescription, a.catid, a.published, a.state, a.publish_up, a.publish_down, a.created_by, a.ordering, a.access, a.params, c.title as cat_name, v.name as author'. //  FROM #__calendar AS a INNER JOIN #__categories AS c ON a.catid = c.id  ORDER BY a.ordering, a.start_date, a.start_time'.
				' FROM #__calendar AS a' .
				' LEFT JOIN #__categories AS c ON c.id = a.catid' .
				' LEFT JOIN #__groups AS g ON g.id = c.access' .
				' LEFT JOIN #__users AS u ON u.id = a.checked_out' .
				' LEFT JOIN #__users AS v ON v.id = a.created_by' .
				//' LEFT JOIN #__content_frontpage AS f ON f.content_id = c.id' .
				$where .
				$order;
		$db->setQuery($query, $pagination->limitstart, $pagination->limit);
		$rows = $db->loadObjectList();

		// If there is a database query error, throw a HTTP 500 and exit
		if ($db->getErrorNum()) {
			JError::raiseError( 500, $db->stderr() );
			return false;
		}

		// get list of categories for dropdown filter
		$query = 'SELECT c.id AS value, c.title AS text, section' .
				' FROM #__categories AS c' .
				' WHERE c.section = '."'com_calendar'".
				' ORDER BY c.title';
		$categories[] = JHTML::_('select.option', '0', '- '.JText::_('Select Category').' -');
		$db->setQuery($query);
		$categories = array_merge($categories, $db->loadObjectList());

		$lists['catid'] = JHTML::_('select.genericlist',  $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active);
		//$lists['catid'] = ContentHelper::filterCategory($query, $catid);

		// get list of sections for dropdown filter
		//$javascript = 'onchange="document.adminForm.submit();"';
		//$lists['sectionid'] = JHTML::_('list.section', 'filter_sectionid', $filter_sectionid, $javascript);

		// get list of Authors for dropdown filter
		/*
		$query = 'SELECT c.created_by, u.name' .
				' FROM #__content AS c' .
				' INNER JOIN #__sections AS s ON s.id = c.sectionid' .
				' LEFT JOIN #__users AS u ON u.id = c.created_by' .
				' WHERE c.state <> -1' .
				' AND c.state <> -2' .
				' GROUP BY u.name' .
				' ORDER BY u.name';
		$authors[] = JHTML::_('select.option', '0', '- '.JText::_('Select Author').' -', 'created_by', 'name');
		$db->setQuery($query);
		$authors = array_merge($authors, $db->loadObjectList());
		$lists['authorid'] = JHTML::_('select.genericlist',  $authors, 'filter_authorid', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'created_by', 'name', $filter_authorid);
		*/
		// state filter
		$lists['state'] = JHTML::_('grid.state', $filter_state, 'Published', 'Unpublished', 'Archived');

		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search'] = $search;
		
		$return_obj = new stdclass();
		$return_obj->rows =& $rows;
		$return_obj->lists =& $lists;
		$return_obj->pagination =& $pagination;
		//ContentView::showContent($rows, $lists, $pagination, $redirect);
		return $return_obj;
	}
	///////////////////////////////////////////////////
	/**
	 * Method to set the article id
	 *
	 * @access	public
	 * @param	int	Article ID number
	 */
	function setId($id)
	{
		// Set new article ID and wipe data
		$this->_id		= $id;
		$this->_article	= null;
	}

	/**
	 * Overridden set method to pass properties on to the article
	 *
	 * @access	public
	 * @param	string	$property	The name of the property
	 * @param	mixed	$value		The value of the property to set
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function set( $property, $value=null )
	{
		if ($this->_loadContent()) {
			$this->_article->$property = $value;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Overridden get method to get properties from the article
	 *
	 * @access	public
	 * @param	string	$property	The name of the property
	 * @param	mixed	$value		The value of the property to set
	 * @return 	mixed 				The value of the property
	 * @since	1.5
	 */
	function get($property, $default=null)
	{
		if ($this->_loadContent()) {
			if(isset($this->_article->$property)) {
				return $this->_article->$property;
			}
		}
		return $default;
	}

	/**
	 * Method to get content article data for the frontpage
	 *
	 * @since 1.5
	 */
	function &getArticle()
	{
		// Load the Category data
		if ($this->_loadArticle())
		{
			$user	= & JFactory::getUser();

			// Is the category published?
			if (!$this->_article->cat_pub && $this->_article->catid) {
				JError::raiseError( 404, JText::_("Article category not published") );
			}
			// Is the section published?
			if ($this->_article->sectionid)
			{
				if ($this->_article->sec_pub === null)
				{
					// probably a new item
					// check the sectionid probably passed in the request
					$db =& $this->getDBO();
					//TODO: 'published' or 'state'?
					$query = 'SELECT published' .
							' FROM #__sections' .
							' WHERE id = ' . (int) $this->_article->sectionid;
					$db->setQuery( $query );
					$this->_article->sec_pub = $db->loadResult();
				}
				if (!$this->_article->sec_pub)
				{
					JError::raiseError( 404, JText::_("Article section not published") );
				}
			}
			// Do we have access to the category?
			if (($this->_article->cat_access > $user->get('aid', 0)) && $this->_article->catid) {
				JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
			}

			// Do we have access to the section?
			if (($this->_article->sec_access > $user->get('aid', 0)) && $this->_article->sectionid) {
				JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
			}

			$this->_loadArticleParams();

			/*
			 * Record the hit on the article if necessary
			 */
			$limitstart	= JRequest::getVar('limitstart',	0, '', 'int');
			if (!$this->_article->parameters->get('intro_only') && ($limitstart == 0))
			{
				$this->incrementHit();
			}

		}
		else
		{
			$article =& JTable::getInstance('content');
			$article->state			= 1;
			$article->cat_pub		= null;
			$article->sec_pub		= null;
			$article->cat_access	= null;
			$article->sec_access	= null;
			$article->author		= null;
			$article->parameters	= new JParameter( '' );
			$article->text			= '';
			$this->_article			= $article;
		}
		return $this->_article;
	}

	/**
	 * Method to increment the hit counter for the article
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function incrementHit()
	{
		global $mainframe;

		if ($this->_id)
		{
			$article = & JTable::getInstance('content');
			$article->hit($this->_id);
			return true;
		}
		return false;
	}
	
	/**
	* for checking on 'checkedout'
	*/
	function _loadEvent($rid)
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_event))
		{
			$query = 'SELECT w.*, cc.title AS category,'.
					' cc.published AS cat_pub, cc.access AS cat_access'.
					' FROM #__calendar AS w' .
					' LEFT JOIN #__categories AS cc ON cc.id = w.catid' .
					' WHERE w.id = '. $rid;
			$this->_db->setQuery($query);
			$this->_event = $this->_db->loadObject();
			return (boolean) $this->_event;
		}
		//return true;
	}

	/**
	 * Tests if article is checked out
	 *
	 * @access	public
	 * @param	int	A user id
	 * @return	boolean	True if checked out
	 * @since	1.5
	 */
	function isCheckedOut( $uid = 0, $rid )
	{
		var_dump('method');
		return false;
		if ($this->_loadEvent($rid))
		{
			if ($uid) {
				return ($this->_event->checked_out && $this->_event->checked_out != $uid);
			} else {
				return $this->_event->checked_out;
			}
		} else {
			JError::raiseWarning( 0, 'Unable to Load Data');
			return false;
		}
		//JError::raiseWarning( 0, 'Unable to Load Data');
			//return false;
		
		//return true;
	}
	
	function checked_out( $uid=0 )
	{
		
		if ($this->_loadEvent())
		{
			if ($uid) {
				return ($this->_event->checked_out && $this->_event->checked_out != $uid);
			} else {
				return $this->_event->checked_out;
			}
		} else {
			JError::raiseWarning( 0, 'Unable to Load Data');
			return false;
		}
		
		//return true;
	}
	
	function getChecked_out( $uid=0 )
	{
		//var_dump($this);
		if ($this->_loadEvent())
		{
			if ($uid) {
				return ($this->_event->checked_out && $this->_event->checked_out != $uid);
			} else {
				return $this->_event->checked_out;
			}
		} else {
			//JError::raiseWarning( 0, 'Unable to Load Data');
			return false;
		}
		
		//return true;
	}

	/**
	 * Method to checkin/unlock the article
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkin()
	{
		if ($this->_id)
		{
			$article = & JTable::getInstance('calendar');
			return $article->checkin($this->_id);
		}
		return false;
	}

	/**
	 * Method to checkout/lock the article
	 *
	 * @access	public
	 * @param	int	$uid	User ID of the user checking the article out
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkout($uid = null)
	{
		if ($this->_id)
		{
			// Make sure we have a user id to checkout the article with
			if (is_null($uid)) {
				$user	=& JFactory::getUser();
				$uid	= $user->get('id');
			}
			// Lets get to it and checkout the thing...
			$article = & JTable::getInstance('calendar');
			return $article->checkout($uid, $this->_id);
		}
		return false;
	}
	/**
	 * Method to checkout/lock the article
	 *
	 * @access	public
	 * @param	int	$uid	User ID of the user checking the article out
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function check_out($uid = null)
	{
		if ($this->_id)
		{
			// Make sure we have a user id to checkout the article with
			if (is_null($uid)) {
				$user	=& JFactory::getUser();
				$uid	= $user->get('id');
			}
			// Lets get to it and checkout the thing...
			$article = & JTable::getInstance('calendar');
			return $article->checkout($uid, $this->_id);
		}
		return false;
	}
	
	
	///////////////////////////////////////
	function saveContentPrep( &$data )
	{

		// Get submitted text from the request variables
		$description = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );

		// Clean text for xhtml transitional compliance
		jimport('joomla.filter.output');
		$description		= str_replace( '<br>', '<br />', $description );
		$title = JRequest::getVar( 'title', '', 'post', 'string', JREQUEST_ALLOWRAW );
		//$data['title']	= JOutputFilter::ampReplace($title);
		//$data['title'] = $this->JS_SpecialChars($data['title']);
		
		// Search for the {readmore} tag and split the text up accordingly.
		$tagPos	= JString::strpos( $description, '<hr id="system-readmore" />' );

		if ( $tagPos === false )
		{
			$data['introdescription']	= $description;
		} else
		{
			$data['introdescription']	= JString::substr($description, 0, $tagPos);
			$data['fulldescription']	= JString::substr($description, $tagPos + 27 );
		}

		return true;
	}
	///////////////////////////////////////

	function store()
{
	jimport('joomla.utilities.date');
	//var_dump('row 306');
	//$user   =& JFactory::getUser();
	//$userid = $user->get('id');
    $row =& $this->getTable();
	
	//var_dump('row 308');
    $data = JRequest::get( 'post' );
	//$data['description'] = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
	//$data['title'] = JRequest::getVar( 'title', '', 'post', 'string', JREQUEST_ALLOWRAW );
	$filter = &JFilterInput::getInstance ($tagsArray = array('i','em'), array(), 0, 0, 1);
	$data['title'] = JRequest::getVar( 'title', '', 'post', 'string', JREQUEST_ALLOWRAW );
	$data['title'] = $filter->_cleanTags($data['title']);
	///////////////////////
//	$filter = &JFilterInput::getInstance ($tagsArray = array('i','em'), $attrArray = ('title'), 0, 0, 1);
//	$data = $filter->_cleanTags($data);

	//////////////////////////////////	
   	$time = JRequest::getVar( 'start_time', '', 'post', 'array' );
	$data['start_time'] = $this->time_selector($time);
	//$data['created_by']
	$params		= JRequest::getVar( 'params', '', 'post', 'array' );
		// Build parameter INI string
		if (is_array($params))
		{
			//$time_str = $params['hour'].":".$params['minute'].":".$params['second'];
			//$ampm = ($params['am_pm'] == 0)? 'AM':'PM'; 
			
			//$paramstamp = mktime ( $params['hour'], $params['minute'], $params['second'], int $month [, int $day [, int $year [, int $is_dst]]]]]]] )
			$param24 = $this->time_selector( array('hours' => $params['hour'], 'minutes' => $params['minute'], 'seconds' => $params['second'], 'am_pm' => $params['am_pm'] ) );
			$data['start_time'] = $param24;
			
			$txt = array ();
			foreach ($params as $k => $v) {
			
				if($k == 'assoc_isbn'){
					$v = $this->cleanISBN($v);
				}
				
				$txt[] = "$k=$v";
				if($k == 'start_date'){
				$data['start_date'] = $v;
				}
			}
			$txt[] = "time=".$time_str;
			//$row->params = implode("\n", $txt);
			$data['params'] = implode("\n", $txt);
			
		}
	//handle text info
	$this->saveContentPrep( $data );
	
	if(empty($params['publish_up'])){
		$data['publish_up'] = date('Y-m-d G:i:s', time());
	}else{
		$data['publish_up']=$params['publish_up'];
	}
	if(empty($params['publish_down'])){
		
		//$day = new JDate('now');
		$day = new JDate($data['start_date'].' 00:00:00');
		$stamp = $day->toUnix();
		$future = $stamp + (24*60*60);
		$day = new JDate($future);
		//$data['publish_down'] = $data['start_date']." ".$data['start_time'];
		$data['publish_down'] = $day->toMySQL();//$data['start_date']." ".$data['start_time'];
	}else{
		$data['publish_down']=$params['publish_down'];
	}
	/**
	 * TODO: implement actual state to work with archiving
	 * TODO: 'published' should be a date that the article was authored?
	 */
	//$data['state'] = $data['published'];
	if (!$row->bind($data)) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }
    // Make sure the hello record is valid
    if (!$row->check()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }

    // Store the web link table to the database
    if (!$row->store()) {
        $this->setError($this->_db->getErrorMsg());
        return false;
    }
	//var_dump('row 692');
    return true;
}

function cleanISBN($input){
		if(is_array($input)){
			foreach($input as $key=>$value){
				//if(preg_match("/^[0-9][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-][0-9-]/",$value) ){
					$input[$key]= str_replace("-","",$value);
				//}//end if
			}//end foreach
		}else{
			$input = str_replace("-","",$input);
		}//end if array
			
		return $input;
	}//end cleanISBN

/**
 * Method to delete record(s)
 *
 * @access    public
 * @return    boolean    True on success
 */
 
function delete()
{
    $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
    $row =& $this->getTable();

    foreach($cids as $cid) {
        if (!$row->delete( $cid )) {
            $this->setError( $row->getErrorMsg() );
            return false;
        }
    }                        

    return true;
}

/**
	 * Method to (un)publish a event
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__calendar'
				. ' SET state = ' . intval( $publish )
				. ' WHERE id IN ( '.$cids.' )'
				//. ' AND ( checked_out = 0 OR ( checked_out = ' .$user->get('id'). ' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

/**
	 * Method to (un)archive a event
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function archive($cid = array(), $archive = -1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__calendar'
				. ' SET state = ' . intval( $archive )
				. ' WHERE id IN ( '.$cids.' )'
				//. ' AND ( checked_out = 0 OR ( checked_out = ' .$user->get('id'). ' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

function update_xml()
{
		//var_dump('update in model');
		//TODO: verify that the arguement is the column, inwhich case it should be 'state'
		$this->_setBuild('Published');
		$data = $this->getData();
		
		$prepared[channel] = array(
				"title" => "BookPeople Events Calendar",
				"link"  => "http://www.bookpeople.com",
				);
		foreach($data as $item){
		$prepared['channel'][] = $item;
		}
		//$prepared[channel] = array($data,		
				
		var_dump('update_xml function 2');
		$xml = $this->xml_serializer($prepared);
		$this->write_xml($xml);
}

function xml_serializer($data)
	{
		var_dump('xml start serial');
		//phpinfo();
		//var_dump()
		//require_once("XML/FS.php");
		//require("/usr/share/pear/PEAR.php");
		var_dump('xml pear force');
		//$classes = get_declared_classes();
		//var_dump($classes);
		//var_dump(file_exists('/usr/share/pear/XML/Serializer.php'));
		require_once('XML/Serializer.php');
		//include_once('Serializer.php');
 		var_dump('xml after include');
		$options = array(
			"addDecl"			=>	'true',
			'defaultTagName'	=>	'item',
			'indent'			=>	'    ',
			"rootName"        => "rss",
      		"rootAttributes"  => array("version" => "2.0"),
			);
 
		// create object
		$serializer = new XML_Serializer($options);
 		var_dump('xml after $serializer');
		// perform serialization
		//$data = htmlspecial($data);
		$serializer->serialize($data);
		$result = $serializer->getSerializedData();
		return $result;
	}

function write_xml($xml)
{
	//require_once("XML/Serializer.php");
	$path = '/var/www/stable/components/com_calendar/public';
	$filename = 'calendar.xml';
	// open file
	if (!$handle = fopen("$path/$filename", 'w')) 
	{ 
	 print "Cannot open file ($filename)";
	 exit;
	}
 
	// write XML to file
	if (!fwrite($handle, $xml)) 
	{
	 print "Cannot write to file ($filename)";
	 exit;
	}
 
	// close file    
	fclose($handle);
}

function time_selector($array = ''){
	if(empty($array)){
	//return a selector	
		//assume 12hr clock
		
		for ($i = 1; $i <= 12; $i++) {
			$hours[$i] = $i;
		}
		
		for ($i = 0; $i <= 59; $i++) {
			$m = (int)$i;
			if((int)$i < 10){
				$m = '0'.(string)$m;
				$minutes[$m] = $m;
			}else{
				$minutes[(string)$m] = (string)$m;
			}//end if less than 10
		}
		
		for ($i = 0; $i <= 59; $i++) {
			$s = (int)$i;
			if((int)$i < 10){
				$s = '0'.(string)$s;
				$seconds[$s] = $s;
			}else{
				$seconds[(string)$s] = (string)$s;
			}//end less than ten
		}
		$am_pm = array('0'=>'AM','1'=>'PM');
		$selector->hours = $hours;
		$selector->minutes = $minutes;
		$selector->seconds = $seconds;
		$selector->am_pm = $am_pm;
		return $selector;
		
	}else{
	//return a string as a mysql time type (hh:mm:dd)
		//add 12 hours if pm
		if($array['am_pm'] == '1'){
			if( (int)$array['hours'] == 12){
				//user selected 12 noon, do nothing
			}else{
				// hours between 1-11 or 13-23
				$array['hours'] = (int)$array['hours'] + 12;
			}
		}else{
			//user select am
			if( (int)$array['hours'] == 12){
				//user selected 12 midnight, 
				$array['hours'] = (int)$array['hours'] + 12;
			}//end hour 12
		}//end 24hr coversion
		
		//change int to string
		if( (int)$array['hours'] == 24){
			$array['hours'] = (string)'00';
		}else{
			$array['hours'] = (string)$array['hours'];
		}//end string convert
		
		$mysql_time= $array['hours'].':'.$array['minutes'].':'.$array['seconds'];
		return $mysql_time;
	}//end if array is empty
	
}//end time_selector method

/*
function event_date_parser($datetime, $task = 'array')
{
	switch($task){
		case 'array':
			//$timestamp = strtotime($datetime);
			//var_dump($timestamp);
			var_dump($datetime);
			//var_dump('switch in');
			//phpinfo();
			//print_r(date_parse("2006-12-12 10:00:00.5"));
			//$format = '%d:%m:%Y %H:%M:%S';
			//$strf = strftime($format);
			//var_dump(strptime($datetime, $format));
			$datetime_array = date_parse($datetime);
			$datetime_array['datetime'] = $datetime;
			var_dump($datetime_array);
			break;
		default:
	}
	return $datetime_array;
}
*/

}
?>
